package com.nj.liandi.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.nj.liandi.common.to.mq.SeckillOrderTo;
import com.nj.liandi.common.utils.R;
import com.nj.liandi.common.vo.MemberRespVo;
import com.nj.liandi.gulimall.seckill.feign.CouponFeignService;
import com.nj.liandi.gulimall.seckill.feign.ProductFeignService;
import com.nj.liandi.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.nj.liandi.gulimall.seckill.service.SeckillService;
import com.nj.liandi.gulimall.seckill.to.SeckillSkuRedisTo;
import com.nj.liandi.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.nj.liandi.gulimall.seckill.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * description: SeckillServiceImpl
 * date: 2021/11/9 16:26
 * author: maizj
 * version: 1.0
 */
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    private final String ACTIVITY_CACHE_PREFIX = "seckill:sessions:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";

    private final String Sku_STOCK_AEMAPHONE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        R r = couponFeignService.getLatest3DaySession();
        if (r.getCode() == 0) {
            List<SeckillSessionsWithSkus> data = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            if (data != null && data.size() > 0) {
                //缓存到redis中
                //1缓存活动的信息
                saveSessionInfos(data);
                //1.缓存活动的关联的商品信息
                saveSessionSkuInfos(data);
            }
        }

    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        long time = new Date().getTime();
        System.out.println("+=="+new Date());
        Set<String> keys = redisTemplate.keys(ACTIVITY_CACHE_PREFIX + "*");
        List<SeckillSkuRedisTo> skuRedisTos = new ArrayList<>();
        for (String key : keys) {
            String replace = key.replace(ACTIVITY_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                //2.获取这个秒杀场次需要的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if (list != null) {
//                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
//                        SeckillSkuRedisTo redisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
//                        return redisTo;
//                    }).collect(Collectors.toList());
                    list.stream().forEach(item->{
                        skuRedisTos.add(JSON.parseObject(item, SeckillSkuRedisTo.class));
                    });
                }
            }
        }
        return skuRedisTos;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInof(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if (keys !=null && keys.size() >0) {
            for (String key : keys) {
                String[] s = key.split("_");
                long l = Long.parseLong(s[1]);
                if (l == skuId){
                    String json = ops.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    if(new Date().getTime() >=redisTo.getStartTime()&&new Date().getTime() <=redisTo.getEndTime()){
                        return redisTo;
                    }else {
                        redisTo.setRandomCode(null);
                        return redisTo;
                    }
                }
            }
        }
        return null;
    }

    //todo 上架秒杀商品的时候,每个数据都要有过期时间,秒杀后续的流程可以补充一下
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();
        //1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = ops.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }else {
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            long time = new Date().getTime();

            long ttl = endTime -time;
            //检验时间合法性
            if (time>=startTime && time <=endTime) {
                String randomCode = redisTo.getRandomCode();
                String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                //检验随机码和商品id
                if (randomCode.equals(key)&&killId.equals(skuId)) {
                    //验证购物数量是否合理
                    if (num <= redisTo.getSeckillLimit().intValue()) {
                        //验证这个人是否已经购买过.幂等性.
                        String  redisKey = respVo.getId()+"_"+skuId;
                        //自动过期
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功说明从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(Sku_STOCK_AEMAPHONE + randomCode);
                                boolean b = semaphore.tryAcquire(num);
                                //秒杀成功,快速下单
                                if (b){
                                    String timeId = IdWorker.getTimeId();
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    orderTo.setOrderSn(timeId);
                                    orderTo.setMemberId(respVo.getId());
                                    orderTo.setNum(num);
                                    orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                    orderTo.setSkuId(redisTo.getSkuId());
                                    orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                    return timeId;
                                }else {
                                    return null;
                                }
                        }else {
                            //说明已经买过了
                            return null;
                        }
                    }
                }else {
                    return null;
                }
            }else {
                return null;
            }
        }
        return null;
    }

    /**
     * description: 保存到redis中活动的基本信息
     * version: 1.0
     * date: 2021/11/9 17:34
     */
    private void saveSessionInfos(List<SeckillSessionsWithSkus> data) {
        data.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = ACTIVITY_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    /**
     * description: 保存到redis中活动的关联的商品的信息
     * version: 1.0
     * date: 2021/11/9 17:33
     */
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> data) {
        //准备hash操作
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        data.stream().forEach(session -> {
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1.sku的基本数据
                    R r = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo info = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(info);
                    }
                    //2.skude 秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);

                    //3.设置上当前的商品的秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    String token = UUID.randomUUID().toString().replace("-", "");
                    //4.随机码
                    redisTo.setRandomCode(token);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), JSON.toJSONString(redisTo));
                    //5.引入分布式信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(Sku_STOCK_AEMAPHONE + token);
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                }
            });
        });
    }
}
